package com.snfdf.camunda.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.spring.annotation.ExternalTaskSubscription;
import org.camunda.bpm.client.task.ExternalTaskHandler;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
@Configuration
public class SelfRepairService implements ApplicationRunner {

    private final RuntimeService runtimeService;

    @ExternalTaskSubscription(topicName = "try_self_repair", processDefinitionKeyIn = {"Process_external_task"}, lockDuration = 5000)
    @Bean
    public ExternalTaskHandler doSelfRepair() {
        return (externalTask, externalTaskService) -> {
            log.info("外部任务进入尝试自修");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            boolean isFree = externalTask.getVariable("isFree");
            if (isFree) {
                log.info("免费维修");
                externalTaskService.handleFailure(externalTask, "维修是免费的，我不想自修了", "这里可以打印异常stacktrace",
                        Optional.ofNullable(externalTask.getRetries()).orElse(5) - 1, 5000);
            } else {
                log.info("收费维修");
                externalTaskService.complete(externalTask);
            }
        };
    }

    @Override
    public void run(ApplicationArguments args) {
        VariableMap variables = Variables.createVariables();
        variables.put("isFree", false);
        runtimeService.startProcessInstanceByKey("Process_external_task", variables);
    }
}
